package LC;

/**
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/
 * Given a sorted linked list, delete all nodes that have duplicate numbers,
 * leaving only distinct numbers from the original list.
 * For example,
 * Given 1->2->3->3->4->4->5, return 1->2->5.
 * Given 1->1->1->2->3, return 2->3.
 */
public class LC_082_RemoveDuplicatesfromSortedListII_LinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(3);
        ListNode h = Solution.deleteDuplicates(head);
        ListNode cur = h;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    static class Solution {
        static ListNode deleteDuplicates(ListNode head) {
            ListNode t = new ListNode(0);
            t.next = head;
            ListNode p = t;
            while (p.next != null && p.next.next != null) {
                if (p.next.val == p.next.next.val) {
                    int dup = p.next.val;
                    while (p.next != null && p.next.val == dup)
                        p.next = p.next.next;
                } else
                    p = p.next;
            }
            return t.next;
        }
    }
}
